package com.linkage.jz.bankruptcy.activity.Project;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FileAdapter;
import com.linkage.jz.bankruptcy.adapter.RecyclerViewAdapter;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProPublic;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPopupMenu;
import com.linkage.jz.bankruptcy.widget.FullyLinearLayoutManager;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;


/**
 * @author AFAP
 * 任务详情
 */
public class ProPublicDetailActivity extends BaseActivity {
    public static final String KEY_ID = "talkid";

    private String mID;
    private ProPublic mPublicDetail;
    private RecyclerView mFileRecyclerView;
    private List<TaskAtta> mFileList = new ArrayList<>();
    private FileAdapter mFileAdapter;

    private TextView tv_public_title, tv_public_type, tv_create_time, tv_public_content, tv_public_number;

    private CommonPopupMenu popupMenu;

    private boolean editOpen = false;
    private boolean deleteOpen = false;
    private boolean showOpenMember = false;

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pro_public_detail);
        super.onCreate(savedInstanceState);
        titlebar_title.setText("公示详情");
        EventBus.getDefault().register(this);
        mID = getIntent().getStringExtra(KEY_ID);

        getDetail();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_PUBLIC)) {
            finish();
        }
    }

    @Override
    public void initView() {
        tv_public_title = findViewById(R.id.tv_public_title);
        tv_public_type = findViewById(R.id.tv_public_type);
        tv_create_time = findViewById(R.id.tv_create_time);
        tv_public_content = findViewById(R.id.tv_public_content);
        tv_public_number = findViewById(R.id.tv_public_number);

        mFileRecyclerView = findViewById(R.id.recycler_files);
        mFileRecyclerView.setLayoutManager(new  LinearLayoutManager(this));
        mFileAdapter = new FileAdapter(this, mFileList);
//        mFileRecyclerView.setLayoutManager(mFileAdapter.createLayoutManager());
        mFileRecyclerView.setAdapter(mFileAdapter);
//        mFileRecyclerView.setHasFixedSize(true);
//        mFileRecyclerView.setNestedScrollingEnabled(false);
    }


    private void refreshDetail() {
        tv_public_title.setText(mPublicDetail.getPublicName());
        tv_public_type.setText(mPublicDetail.getPublicType());
        tv_create_time.setText(DateFormatUtils.long2Str(mPublicDetail.getOpAt() * 1000, true));
        tv_public_content.setText(mPublicDetail.getPublicDetail());
        tv_public_number.setText(mPublicDetail.getNumber() + "人");
        tv_public_number.setOnClickListener(v -> {
            if (!showOpenMember) {
                ToastUtil.showShort("您没有查看权限");
                return;
            }

            if (mPublicDetail.getNumber() > 0) {
                Intent intent = new Intent(ProPublicDetailActivity.this, ProPublicViewMemberActivity.class);
                intent.putExtra(ProPublicViewMemberActivity.KEY_PUBLIC, mPublicDetail);
                startActivity(intent);
            }
        });

        if (mPublicDetail.getAttachmentList() != null) {
            mFileList.addAll(mPublicDetail.getAttachmentList());
            FileAdapter.sorFiles(mFileList, false);
            mFileAdapter.notifyDataSetChanged();
        }

        List<String> menus = new ArrayList<>();
        if (editOpen) {
            menus.add("编辑");
        }
        if (deleteOpen) {
            menus.add("删除");
        }
        if (menus.size() == 0) {
            titlebar_menu.setVisibility(View.GONE);
            return;
        }

        popupMenu = new CommonPopupMenu(this, menus);
        titlebar_menu.setVisibility(View.VISIBLE);
        titlebar_menu.setOnClickListener(v -> {
            popupMenu.showLocation(R.id.titlebar_menu);
            popupMenu.setOnItemClickListener((index, str) -> {
                if (TextUtils.equals(str, "编辑")) {
                    Intent intent = new Intent(ProPublicDetailActivity.this, CreateProPublicActivity.class);
                    intent.putExtra(CreateProPublicActivity.KEY_ACTION, "edit");
                    intent.putExtra(CreateProPublicActivity.KEY_PUBLIC, mPublicDetail);
                    startActivity(intent);
                } else if (TextUtils.equals(str, "删除")) {
                    Dialog tipDialog = new AlertDialog
                            .Builder(ProPublicDetailActivity.this)
                            .setTitle("提示")
                            .setMessage("确认删除当前记录吗？")
                            .setPositiveButton(R.string.confirm, (dialog, which) -> deletePublic()).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();

                    tipDialog.setCancelable(false);
                    tipDialog.show();
                }

            });

        });
    }


    private void getDetail() {
        Network
                .getAPIService()
                .getPublicDetail(getUserToken(), mID)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mShapeLoadingDialog.show();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        editOpen = data.getAsJsonObject("auth").get("editOpen").getAsBoolean();
                        deleteOpen = data.getAsJsonObject("auth").get("deleteOpen").getAsBoolean();
                        showOpenMember = data.getAsJsonObject("auth").get("showOpenMember").getAsBoolean();

                        mPublicDetail = ProPublic.parse(data.getAsJsonObject("publicInfo"));

//                        editOpen = false;
//                        deleteOpen = false;
//                        showOpenMember = false;
                        refreshDetail();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }


    private void deletePublic() {
        Network
                .getAPIService()
                .deletePublic(getUserToken(), mID)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(() -> mShapeLoadingDialog.show())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_PUBLIC);
                        EventBus.getDefault().post(event);
//                        ToastUtil.showShort("数据已删除");
                        showToast("公示删除成功", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.SUCCESS);
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }
}
